import path from 'path';
import mongoose, { Connection } from 'mongoose';
import { dbConfig } from '../config/db';
import  { isPro } from '../util/env';

const { dbConfigInfo, database } = dbConfig;

// mongodb连接url
const connectUrl = `mongodb://${dbConfigInfo.dbUrl}:${dbConfigInfo.dbPort}?authSource=wisdom`;

let instance: Connection;
let username = '';
let password = '';
// 非正式环境使用本地的json文件中的用户名，密码。这个文件默认不上传git
let dbAuthJson = {
  username: '',
  password: '',
};

try {
  // if (!isPro) {
  //   dbAuthJson = require(path.resolve('./db.auth.json'));
  // }
  // 生产环境和本地环境先都从这里读取数据，为了安全这里应该放到更合适的地方，日后更改
  dbAuthJson = require(path.resolve('./db.auth.json'));
  username = process.env.dbuser || dbAuthJson.username;
  password = process.env.dbpass || dbAuthJson.password;
} catch (error) {
  console.log('get db username password error, info:', error);
}

function createConnect(): Connection | {
  then: Promise<Connection>['then']
  catch: Promise<Connection>['catch']
} {
  mongoose.set('bufferTimeoutMS', 60000);
  return mongoose.createConnection(connectUrl, { 
    dbName: database,
    user: username,
    pass: password,
  });
}

// 获取实例
export async function getInstance(): Promise<Connection> {
  if (!instance) {
    instance = await createConnect();
  }
  return instance;
}